package com.wwlwxg.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SecondRealm extends AuthenticatingRealm {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		log.info("SecondRealm ------> doGetAuthenticationInfo " + token + " : enter......");
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = upToken.getUsername();
		log.info("SecondRealm ------> 从数据库获取username ： " + username + " 所对应的信息。");
		
		if("unkown".equals(username)) {
			throw new UnknownAccountException("用户名不存在.......");
		}
		
		if("monster".equals(username)) {
			throw new LockedAccountException("用户被锁定......");
		}
		
		Object principal = username;
		Object credentials = "fc1709d0a95a6be30bc5926fdb7f22f4";
		if("admin".equals(username)) {
			credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
		} else if("user".equals(username)){
			credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
		}
		String realmName = getName();
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		
		return new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
	}
	
	public static void main(String[] args) {
		
		String algorithmName = "SHA1";
		Object source = "123456";
		Object salt = "user";
		int hashIterations = 1024;
		
		Object result = new SimpleHash(algorithmName, source, salt, hashIterations);
		System.err.println(result);
	}

}
